// pages/we/adddiary/adddiary.js
import util from "../../../utils/util.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tempfiles: [], // 存放选中的图片或者视频
    fileids: [],   // 上传到云后的全部url
    sources: [],  // 用于预览的资源
    canChoose: true, // 是否还能选择
    diary: '',
    type: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  getInput(e) {
    this.setData({
      diary: e.detail.value
    })
  },
  chooseImg() { // 选取图片
    wx.chooseMedia({
      count: 9 - this.data.tempfiles.length,
      mediaType: ['image'],
      sourceType: ['album'],
      sizeType: ['compressed'],
      success: res => {
        this.data.tempfiles = this.data.tempfiles.concat(res.tempFiles)
        this.setData({
          tempfiles: this.data.tempfiles,
          type: res.type,
          canChoose: this.data.tempfiles.length == 9 ? false : true
        })
      },
      fail: res => {
        console.log("选择失败", res)
      }
    })
  },
  chooseVideo() {   // 选取视频
    if (this.data.tempfiles.length > 0) {
      wx.showToast({
        icon: 'none',
        title: '如需添加视频请先删除之前的图片哦',
        duration: 3000
      })
      return
    }
    wx.chooseMedia({
      count: 1,
      mediaType: ['video'],
      sourceType: ['album'],
      success: res => {
        this.setData({
          tempfiles: res.tempFiles,
          type: res.type,
          canChoose: false
        })
      },
      fail: res => {
        console.log("选择失败", res)
      }
    })
  },
  preview(e) {
    let index = e.currentTarget.dataset.index
    this.data.sources = []
    this.data.tempfiles.forEach(item => { // 希望微信官方可以修改一下 这个接口 还要重新写一个source 真的太麻烦了
      this.data.sources.push({
        url: item.tempFilePath,
        type: this.data.type
      })
    })
    wx.previewMedia({
      sources: this.data.sources,
      type: this.data.sources[index].type,
      url: this.data.sources[index].url,
      current: index,
      success: res => {
      },
      fail: res => {
      }
    })
  },
  Del(e) {
    this.data.tempfiles.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      tempfiles: this.data.tempfiles,
      canChoose: true,
      type: this.data.length == 0? '' : this.data.type //没有视频或者图片就没有type了 否则就保持原样
    })
  },
  openDialog() { // 显示选择框
    this.setData({
      showDialog: true,
    });
  },
  close() {  // 关闭选择框
    this.setData({
      showDialog: false,
    });
  },
  addDiary() {
    if (this.data.diary == '') {
      wx.showToast({
        icon: 'error',
        title: '日记内容为空',
      })
      return
    }
    wx.showLoading({
      title: '上传中',
    })
    this.upload(this.data.type, this.data.tempfiles, 0)   // 上传到数据库
  },
  upload(type, tempfiles, index) { // type = image  或者 video
    if (index == tempfiles.length) {
      var date = new Date
      const year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()
      if(month < 10) month = "0" + month
      if(day < 10) day = "0" + day
      var DATE = year + '年' + month + '月' + day + '日'
      if(this.data.type == 'video') {
        this.data.fileids.push(this.data.tempfiles[0].thumbTempFilePath)
      }
      wx.cloud.database().collection('diary').add({
        data: {
          lover_openid: wx.getStorageSync('lover')._openid,
          time: DATE,
          createTime: Date.parse(new Date()),
          diary: this.data.diary,
          type: type,
          urls: this.data.fileids
        }
      }).then(res => {
        wx.hideLoading()
        wx.reLaunch({
          url: '/pages/we/diary/diary',
        })
      })
      return
    } else {
      let path = tempfiles[index].tempFilePath
      path = Date.parse(new Date()) + path.substr(path.length - 10, 10)  //云上的文件名
      wx.cloud.uploadFile({
        cloudPath: type + '/' + path,
        filePath: tempfiles[index].tempFilePath,
        success: res => {
          this.data.fileids.push(res.fileID)
          this.upload(type, tempfiles, ++index)
        }
      })
    }
  },
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})